package com.qf.fmcommodity.interce;

import cn.hutool.jwt.JWT;
import com.qf.fmcommodity.user.utils.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class CheckTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取token
        String token = request.getHeader("token");
        //如果请求头中没有携带token，则直接拒绝请求
        if (token == null || "".equals(token)) {
            log.debug("没有token");
            return false;
        }

        //校验token合法性
        boolean validate = JWT.of(token).setKey(Constants.SECRET.getBytes("utf-8"))
                .validate(0);
        if (validate) {
            log.debug("token 校验通过");
            return true;
        }else {
            log.debug("token 校验失败");
            return false;
        }
    }
}
